#include <stdlib.h>
#include <pthread.h>
#include "cabuffer.h"
#include "calog.h"

int es_bufman_init(es_bufman_t* pman, int size)
{
	memset(pman, 0, sizeof(es_bufman_t));
	pman->res = (lklist*)malloc(sizeof(lklist)*size);
	if(!pman->res)
		return -1;
	pman->size = size;	
	pman->free_bufs = pman->res;
	lkinit(pman->free_bufs);
	for(int i=1;i<size;i++)
	{
		lkadd(pman->free_bufs, pman->res+i);
	}

	pthread_mutex_init(&pman->mutex, NULL);

	return 0;
	
}


lklist* es_bufman_get(es_bufman_t* pman)
{
	lklist* ibuf;
	pthread_mutex_lock(&pman->mutex);
	ibuf = pman->free_bufs;
	if(ibuf)
	{
		pman->free_bufs = lkpop_head(pman->free_bufs);
		pman->count++;
	}
	else if(pman->fill_bufs)
	{
		logprt("### no empty buf...\n");
		ibuf = pman->fill_bufs;
		pman->fill_bufs = lkpop_head(pman->fill_bufs);
	}
	
	pthread_mutex_unlock(&pman->mutex);
	return ibuf;
}


void es_bufman_return(es_bufman_t* pman, lklist* pitem)
{
	pthread_mutex_lock(&pman->mutex);
	if(pman->free_bufs == NULL)
	{
		lkinit(pitem);
		pman->free_bufs = pitem;
	}
	else
		lkadd(pman->free_bufs, pitem);
	pman->count--;	
	pthread_mutex_unlock(&pman->mutex);
	
}


void es_bufman_push(es_bufman_t* pman, lklist* p)
{
	pthread_mutex_lock(&pman->mutex);
	if(pman->fill_bufs)
		lkadd(pman->fill_bufs, p);
	else {
		lkinit(p);
		pman->fill_bufs = p;
	}
	pthread_mutex_unlock(&pman->mutex);
}

lklist* es_bufman_pop(es_bufman_t* pman)
{
	lklist* ibuf;
	pthread_mutex_lock(&pman->mutex);
	ibuf = pman->fill_bufs;
	if(ibuf)
		pman->fill_bufs = lkpop_head(pman->fill_bufs);
	pthread_mutex_unlock(&pman->mutex);
	return ibuf;

}


void es_bufman_free(es_bufman_t* pman)
{
	free(pman->res);
	memset(pman, 0, sizeof(es_bufman_t));
}

